package com.xiang.encodetool.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class UTF8Parser {

    private String curEncode;
    private String targetEncode;

    public UTF8Parser(String curEncode, String targetEncode) {
        this.curEncode = curEncode;
        this.targetEncode = targetEncode;
    }

    /**
     * 目录就迭代遍历；文件就重编码
     * @param files  要转换的文件
     * @param path  转换后存放的的路径
     * @throws IOException
     */
    public void parse(File[] files, String path) throws IOException {
        for (File file : files) {
            if (!file.isDirectory()) {
                File destFile = new File(path, file.getName());
                parse2UTF_8(file, destFile);
            } else {
                parse(file.listFiles(), path+file.getName());
            }
        }
    }


    /**
     * 转码
     * @param file  目标文件
     * @param destFile  转码后存到此文件
     * @throws IOException  读写文件可能发生IO异常
     */
    private void parse2UTF_8(File file, File destFile) throws IOException {
        StringBuffer msg = new StringBuffer();
        //读写对象
        PrintWriter ps = new PrintWriter(new OutputStreamWriter(new FileOutputStream(destFile, false), targetEncode));
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), curEncode));

        //读写动作
        String line = br.readLine();
        while (line != null) {
            msg.append(line).append("rn");
            line = br.readLine();
        }
        ps.write(msg.toString());
        br.close();
        ps.flush();
        ps.close();
    }

}